<?php
namespace app\service\productAvatar;

use think\facade\Db;
use app\service\TopviewApiService;
use app\service\PointsService;

class ProductAvatar
{
    private $apiService;
    private $pointsService;

    public function __construct()
    {
        $this->apiService = new TopviewApiService();
        $this->pointsService = new PointsService();
    }

    /**
     * 创建营销视频任务（第一阶段：图片替换）
     */
    public function createTask($userId, $params)
    {
        // 验证必填参数
        if (empty($params['productImageFileId'])) {
            throw new \Exception('产品图片ID不能为空');
        }
        // if (empty($params['imageEditPrompt'])) {
            // throw new \Exception('图片编辑提示不能为空');
        // }
        if (empty($params['avatarId']) && empty($params['templateImageFileId'])) {
            throw new \Exception('头像ID和模板图片ID至少需要一个');
        }

        // 获取积分配置
        $pointsConfig = config('points.points.marketing_avatar.image_replace');
        $needPoints = $pointsConfig['points'];

        // 检查用户积分
        $userPoints = $this->pointsService->getUserPoints($userId);
        if ($userPoints < $needPoints) {
            throw new \Exception("积分不足，需要{$needPoints}积分，当前余额{$userPoints}积分");
        }

        Db::startTrans();
        try {
            // 扣除积分
            $this->pointsService->consume($userId, $needPoints, $pointsConfig['name']);

            // 第一步：提交去背景任务
            $bgSubmit = $this->apiService->submitRemoveBackgroundTask([
                'productImageFileId' => $params['productImageFileId']
            ]);

            // 创建统一任务记录
            $taskId = Db::name('marketing_video_unified_tasks')->insertGetId([
                'task_name' => $params['taskName'] ?? '营销视频任务',
                'user_id' => $userId,
                
                // 第一阶段参数
                'avatar_id' => $params['avatarId'],
                'product_image_file_id' => $params['productImageFileId'],
                'template_image_file_id' => $params['templateImageFileId'],
                'user_face_image_file_id' => $params['userFaceImageFileId'],
                'image_edit_prompt' => $params['imageEditPrompt'],
                
                // 去背景阶段
                'bg_remove_task_id' => $bgSubmit['result']['taskId'] ?? null,
                'bg_remove_status' => 1, // 处理中

                // 第一阶段状态（等待去背景完成后再提交图片替换）
                'replace_task_id' => null,
                'replace_status' => 0, // 待处理
                'overall_status' => 1, // 图片替换中
                
                // 积分记录
                'replace_points_consumed' => $needPoints,
                'total_points_consumed' => $needPoints,
                
                'create_time' => date('Y-m-d H:i:s')
            ]);

            Db::commit();

            return [
                'task_id' => $taskId,
                // 保持出参不变：此时还未提交替换任务，先返回空，待定时任务提交后再更新DB
                'replace_task_id' => null,
                // 'consumed_points' => $needPoints,
                // 'remaining_points' => $userPoints - $needPoints
            ];

        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 开始视频生成（第二阶段：图片转视频）
     */
    public function startVideoGeneration($userId, $taskId, $params)
    {
        // 获取任务
        $task = Db::name('marketing_video_unified_tasks')
            ->where(['id' => $taskId, 'user_id' => $userId])
            ->find();

        if (!$task) {
            throw new \Exception('任务不存在');
        }

        if ($task['replace_status'] != 2) {
            throw new \Exception('图片替换未完成，无法开始视频生成');
        }

        if ($task['video_status'] != 0) {
            throw new \Exception('视频生成已开始或已完成');
        }

        // 验证参数
        if (empty($params['selectedResultKey'])) {
            throw new \Exception('请选择替换结果图片');
        }
        // if (empty($params['mode']) || !in_array($params['mode'], ['lite', 'pro'])) {
            // throw new \Exception('模式必须是 lite 或 pro');
        // }
        // if (empty($params['voiceoverId'])) {
            // throw new \Exception('配音ID不能为空');
        // }

        // 获取积分配置
        $params['mode'] = "pro";
        $pointsConfig = config('points.points.marketing_avatar.image2video.' . $params['mode']);
        $needPoints = $pointsConfig['points'];

        // 检查用户积分
        $userPoints = $this->pointsService->getUserPoints($userId);
        if ($userPoints < $needPoints) {
            throw new \Exception("积分不足，需要{$needPoints}积分，当前余额{$userPoints}积分");
        }

        Db::startTrans();
        try {
            // 扣除积分
            $this->pointsService->consume($userId, $needPoints, $pointsConfig['name']);

            // 调用API提交视频生成任务
            $apiParams = [
                'replaceProductTaskImageId' => $params['selectedResultKey'],
                'mode' => $params['mode'],
                'scriptMode' => $params['scriptMode'],
                'voiceId' => $params['voiceoverId'],
                'ttsText' => $params['ttsText'],
                'audioFileId' => $params['audioFileId']
            ];
            $result = $this->apiService->submitImage2VideoTask($apiParams);

            // 更新任务记录
            Db::name('marketing_video_unified_tasks')
                ->where('id', $taskId)
                ->update([
                    'selected_result_key' => $params['selectedResultKey'],
                    'video_mode' => $params['mode'],
                    'image2video_prompt' => $params['image2videoPrompt'],
                    'voiceover_id' => $params['voiceoverId'],
                    'tts_text' => $params['ttsText'],
                    
                    'video_task_id' => $result['taskId'],
                    'video_status' => 1, // 处理中
                    'overall_status' => 3, // 视频生成中
                    
                    // 'video_points_consumed' => $needPoints,
                    // 'total_points_consumed' => $task['total_points_consumed'] + $needPoints,
                    'update_time' => date('Y-m-d H:i:s')
                ]);

            Db::commit();

            return [
                'video_task_id' => $result['taskId'],
                // 'consumed_points' => $needPoints,
                // 'remaining_points' => $userPoints - $needPoints
            ];

        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 获取任务列表
     */
    public function getTaskList($userId, $page = 1, $pageSize = 10)
    {
        $list = Db::name('marketing_video_unified_tasks')
            ->where('user_id', $userId)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select()
            ->each(function($item) {
                // 格式化时间
                $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
                if ($item['replace_complete_time']) {
                    $item['replace_complete_time'] = date('Y-m-d H:i:s', strtotime($item['replace_complete_time']));
                }
                if ($item['video_complete_time']) {
                    $item['video_complete_time'] = date('Y-m-d H:i:s', strtotime($item['video_complete_time']));
                }
                
                // 解析结果图片
                if (!empty($item['result_images'])) {
                    $item['result_images'] = json_decode($item['result_images'], true);
                }
                
                // 格式化状态文本
                $statusMap = [
                    1 => '图片替换中',
                    2 => '图片替换完成',
                    3 => '视频生成中',
                    4 => '全部完成',
                    5 => '失败'
                ];
                $item['overall_status_text'] = $statusMap[$item['overall_status']] ?? '未知';
                
                return $item;
            });

        $total = Db::name('marketing_video_unified_tasks')
            ->where('user_id', $userId)
            ->count();

        return [
            'list' => $list,
            'pagination' => [
                'page' => $page,
                'page_size' => $pageSize,
                'total' => $total,
                'total_pages' => ceil($total / $pageSize)
            ]
        ];
    }

    /**
     * 获取任务详情
     */
    public function getTaskDetail($userId, $taskId)
    {
        $task = Db::name('marketing_video_unified_tasks')
            ->where(['id' => $taskId, 'user_id' => $userId])
            ->find();

        if (!$task) {
            throw new \Exception('任务不存在');
        }

        // 解析结果图片
        if (!empty($task['result_images'])) {
            $task['result_images'] = json_decode($task['result_images'], true);
        }

        return $task;
    }
} 